package com.ynet.middleground.riskmanage.utils;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.namespace.QName;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ynet.cache.redis.IfpRedisson;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.riskmanage.dao.ServiceLogMapper;
import com.ynet.middleground.riskmanage.entity.ServiceLog;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.hangxin.HangXinUriEnum;

@Component
public class WebServiceUtil {
    @Autowired
    MainBusinessConfig mainBusinessConfig;

    @Autowired
    private ServiceLogMapper serviceLogMapper;

    @Autowired
    private IfpRedisson redisson;

    private static final String Algorithm = "DESede"; // 定义 加密算法,可用 DES,DESede,Blowfish

    /**
     * redis 全局日志记录开关
     */
    public static String REDIS_KEY = "ifp:system:settings:logswitch";

    public String HxWebUtil(HangXinUriEnum method, String arg0, BaseReqObj reqObj, String shmw) {
        try {
            String endpoint = mainBusinessConfig.getHangxinWsdlUrl();
            // 直接引用远程的wsdl文件
            // 以下都是套路
            Service service = new Service();
            Call call = (Call)service.createCall();
            call.setTargetEndpointAddress(endpoint);
            call.setEncodingStyle("GBK");
            // call.setOperationName("YFPCXService");//WSDL里面描述的接口名称
            call.setOperationName(new QName(mainBusinessConfig.getHangxinNamespaceUrl(), method.getUrl()));// 调用的方法名
            call.addParameter("arg0", org.apache.axis.encoding.XMLType.XSD_DATE, javax.xml.rpc.ParameterMode.IN);// 接口的参数
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
            // String temp = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
            // "<FPXT_INPUT>\n" +
            // " <ID>DLSB</ID>\n" +
            // " <SHMW>PKKQ78hrc0a4mfHZwCgoTbsV40vhgPBj</SHMW>\n" +
            // "
            // <DATA>PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iR0JLIj8+CjxJTlBVVD4gCjxTSD7nqI7lj7c8L1NIPiAgCjxaRkpIPuS4u+WIhuacuuWPtzwvWkZKSD4gCjwvSU5QVVQ+Cg==</DATA>\n"
            // +
            // "</FPXT_INPUT>";
            // 方法开始执行的时间
            long startTime = System.currentTimeMillis();
            String temp = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" + "<FPXT_INPUT>\n" + "\t<ID>" + method.getId()
                + "</ID>\n" + "\t<SHMW>" + shmw + "</SHMW>\n" + "\t<DATA>" + arg0 + "</DATA>\n" + "</FPXT_INPUT>\n";
            IfpLogger.info("HxWebUtil", "航信本次请求信息:" + endpoint + temp);
            String result = (String)call.invoke(new Object[] {temp});// 给方法传递参数，并且调用方法
            IfpLogger.info("HxWebUtil", "航信本次响应信息:" + result);
            // 记录方法正常执行后时间
            long methodEnd = System.currentTimeMillis();
            ServiceLog log = new ServiceLog();
            log.setServiceCode(method.getCode());
            log.setRequestMsg(temp);
            log.setResponseMsg(result);
            log.setResDate(LocalDateTime.now());
            log.setChannel(reqObj.getChannel());
            log.setCostTime(Math.toIntExact((methodEnd - startTime)));
            log.setGmtCreate(LocalDateTime.now());
            log.setCreateBy(reqObj.getOperationUserId());
            log.setGmtModified(LocalDateTime.now());
            log.setModifiedBy(reqObj.getOperationUserId());
            serviceLogMapper.insert(log);
            return result;
        } catch (Exception e) {
            return e.toString();
        }
    }

    /**
     * base64 加密
     *
     * @param str
     * @return
     */
    public static String base64Encoder(String str) {
        if (StringUtils.isWhitespace(str)) {
            return null;
        }
        String returnStr = null;
        byte[] bytes = new byte[0];
        try {
            bytes = org.apache.commons.codec.binary.Base64.encodeBase64(str.getBytes("GBK"));
            returnStr = new String(bytes, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnStr;
    }

    /**
     * base64 解密
     *
     * @param str
     * @return
     */
    public static String base64Decoder(String str) {
        if (StringUtils.isWhitespace(str)) {
            return null;
        }
        String decodeStr = null;
        byte[] bytes = new byte[0];
        try {
            bytes = org.apache.commons.codec.binary.Base64.decodeBase64(str.getBytes("GBK"));
            decodeStr = new String(bytes, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return decodeStr;
    }

    /**
     * 3des 加密
     * 
     * @param key
     * @param text
     * @return
     * @throws Exception
     */
    public static String encrypt(String key, String text) throws Exception {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(text)) {
            return null;
        }
        // 生成密钥
        SecretKey deskey = new SecretKeySpec(key.getBytes(), Algorithm);
        // 加密
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bytes = c1.doFinal(text.getBytes());
        return new String(bytes, "GBK");
    }

    /**
     * 3des加密 后 Base64加密
     * 
     * @param key
     * @param text
     * @return
     * @throws Exception
     */
    public static String threeDesAndBase64(String key, String text) throws Exception {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(text)) {
            return null;
        }
        // 生成密钥
        SecretKey deskey = new SecretKeySpec(key.getBytes(), Algorithm);
        // 加密
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bytes = c1.doFinal(text.getBytes("GBK"));
        byte[] base64 = org.apache.commons.codec.binary.Base64.encodeBase64(bytes);
        return new String(base64, "GBK");
    }

    public static void main(String[] args) throws Exception {
        String xml =
            "eyJEQVRBIjp7IkFMTENPVU5UIjoiMiIsIlJFRElOVlJFUUJJTEwiOlt7IlJFUUJJTExOTyI6IjY2MTAwNjU1MTc5MjIxMTIwNzExMTY1MCIsIlJFU0JJTExOTyI6IjM3MDI5NjIxMTIwMDY3ODQiLCJTVEFUVVNETSI6IlRaRDAwODUiLCJTVEFUVVNNQyI6IuafpeivgeacqumAmui/hyIsIkJJTEx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MjExMjA2IiwiWEZTSCI6IjkxMzcwMjExTUEzUldXTE0ySyIsIlhGTUMiOiLlsbHkuJzpmYbmtbfogZTliqjln7rph5HnrqHnkIbmnInpmZDlhazlj7giLCJHRlNIIjoiOTExMTAxMDg1OTk2OTg5ODU0IiwiR0ZNQyI6IuWMl+S6rOaYk+ivmuS6kuWKqOe9kee7nOaKgOacr+iCoeS7veaciemZkOWFrOWPuCIsIkhKSkUiOi0xLjAsIkhKU0UiOi0wLjEzLCJHRkRaREgiOiIiLCJHRllIWkgiOiIiLCJSRVFNRU1PIjoiTjUiLCJCTUJCSCI6IjMzLjAiLCJZWVNCWiI6IjAwMDAwMDAwMDAiLCJZREJTIjoiMCIsIkRLQkRCUyI6IjAiLCJSRURJTlZSRVFCSUxMTVgiOlt7IlhNTUMiOiLpk6znn7/nn7MiLCJKTERXIjoi5ZCoIiwiR0dYSCI6IlQwLTEiLCJYTURKIjoxLjAsIlhNSkUiOi0xLjAsIlhNU0wiOi0xLjAsIlNMIjowLjEzLCJTRSI6LTAuMTMsIlNQQk0iOiIxMDIwMzAzMDAwMDAwMDAwMDAwIiwiUVlaWEJNIjoiIiwiU0ZZSFpDIjoiMCIsIllIWkNOUiI6IiIsIkxTTEJTIjoiIn1dfV19LCJSRVRVUk4iOnsiQ09ERSI6IjAwMDAwMCIsIk1FU1MiOiLmiJDlip8ifX0=";
        byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(xml.getBytes("GBK"));
        String a = new String(bytes);
        System.out.println(a);

        // String token = "MEGKDFEEMAGRWWLMFKFDDDEL";

        // String token = "MEGKDFEEMAGRWWLMFKFDDDEL";
        // String sh = "91370211MA3RWWLM2K";
        // String a = WebServiceUtil.encrypt(token, sh);
        // System.out.println("3des加密：" + a);
        // String b = WebServiceUtil.base64Encoder(sh);
        // System.out.println("base64加密：" + b);
        // System.out.println("先后加密：" + WebServiceUtil.base64Encoder(WebServiceUtil.encrypt(token, sh)));
        // String c = WebServiceUtil.threeDesAndBase64(token, sh);
        // System.out.println("加密后" + c);
    }

}